﻿using Architecture.Domain.Services.Impl;
using Architecture.Domain.Services.Interface;
using Architecture.Domain.TraceabilityManage;
using Architecture.Domian.Entity;
using Architecture.Repository;
using Architecture.Repository.Impl;
using Architecture.Repository.Interface;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System.Text;

namespace Architecture.Api.Extensions
{
    public static partial class ServiceCollectionExtensions
    {
        /// <summary>
        /// 注册数据库上下文
        /// </summary>
        /// <typeparam name="TDbContext"></typeparam>
        /// <param name="services"></param>
        /// <param name="connectionString"></param>
        /// <param name="enableSqlLog"></param>
        /// <returns></returns>
        public static IServiceCollection AddDbContextService<TDbContext>(this IServiceCollection services, string? connectionString, bool enableSqlLog) where TDbContext : DbContext
        {
            return services.AddDbContext<TDbContext>(builder =>
            {
                builder.UseSqlServer(connectionString, action =>
                {
                    action.EnableRetryOnFailure(
                        maxRetryCount: 10,
                        maxRetryDelay: TimeSpan.FromSeconds(60),
                        errorNumbersToAdd: null);
                }).EnableSensitiveDataLogging();
                if (enableSqlLog)
                {
                    builder.UseLoggerFactory(LoggerFactory.Create(configure =>
                    {
                        configure
                        .AddFilter((category, level) => category == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information)
                        .AddConsole();
                    }));
                }
            });
        }

        /// <summary>
        /// 注册JWT
        /// </summary>
        /// <param name="services"></param>
        /// <param name="builder"></param>
        public static void AddJWT(this IServiceCollection services, WebApplicationBuilder builder)
        {
            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    //取出私钥
                    var secretByte = Encoding.UTF8.GetBytes(builder.Configuration["Authentication:SecretKey"]);
                    options.TokenValidationParameters = new TokenValidationParameters()
                    {
                        //验证发布者
                        ValidateIssuer = true,
                        ValidIssuer = builder.Configuration["Authentication:Issuer"],
                        //验证接收者
                        ValidateAudience = true,
                        ValidAudience = builder.Configuration["Authentication:Audience"],
                        //验证是否过期
                        ValidateLifetime = true,
                        //验证秘钥
                        IssuerSigningKey = new SymmetricSecurityKey(secretByte)
                    };
                });
        }

        /// <summary>
        /// 注册服务
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddServices(this IServiceCollection services)
        {
            services.AddScoped<EFCoreDbContext>();
            services.AddTransient(typeof(IRepository<>), typeof(BaseRepository<>));
            services.AddScoped<IUserRepository, UserRepository>();
            services.AddScoped<IRoleRepository, RoleRepository>();
            services.AddScoped<IMenuRepository, MenuRepository>();
            services.AddScoped<ISourceRepository, SourceRepository>();
            services.AddScoped<IUserService, UserService>();
            services.AddScoped<IRoleSerivce, RoleService>();
            services.AddScoped<IMenuService, MenuService>();
            services.AddScoped<ISourceService, SourceService>();
            services.AddScoped<ICultureRepository, CultureRepository>();
            services.AddScoped<ICultureService, CultureService>();
            services.AddScoped<ICorporationRepository, CorporationRepository>();
            services.AddScoped<ISlaughterService, SlaughterService>();
            services.AddScoped<ISlaughterRepository, SlaughterRepository>();
            services.AddScoped<IImmuneInformationRepository, ImmuneInformationRepository>();
            services.AddScoped<IDeepProcessingService, DeepProcessingService>();
            services.AddScoped<IDeepProcessingRepository, DeepProcessingRepository>();
            services.AddScoped<ISupplierRepository, SupplierRepository>();
            return services;
        }
    }
}
